package com.sinaapp.aidaka.server.controller;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import com.sinaapp.aidaka.server.domain.User;
import com.sinaapp.aidaka.server.service.UserService;

@Controller
@RequestMapping("/user")
public class UserController {
	
	private static final String PAGE_USER_HOME = "user/success";
	private static final String PAGE_REGISTER = "user/register";
	private static final String PAGE_ACTIVE_EMAIL = "user/ac_email";
	private static final String PAGE_LOGIN = "user/login";

	@Autowired
	private UserService userService;
	
	@RequestMapping("/register")
	public String goRegister() {
		return PAGE_REGISTER;
	}
	
	@RequestMapping(value="/doregister", method=RequestMethod.POST)
	public ModelAndView registerNewUser(
			HttpServletRequest request,
			@RequestParam("email") String email,
			@RequestParam("password") String password,
			@RequestParam("conf_password") String conPassword
			)  {
		ModelAndView modelAndView = new ModelAndView();
		if(!password.equals(conPassword)) {
			modelAndView.setViewName(PAGE_REGISTER);
			modelAndView.addObject("info", "两次输入的密码不一样！");
			return modelAndView;
		}
		if(userService.isEmailExists(email)){
			modelAndView.setViewName(PAGE_REGISTER);
			modelAndView.addObject("info", "email已存在");
			return modelAndView;
		}
		userService.newUser(email, password, request.getRemoteAddr());
		User user = userService.login(email, password, request.getRemoteAddr());
		modelAndView.setViewName(PAGE_ACTIVE_EMAIL);
		request.getSession().setAttribute("user", user);
		return modelAndView;
	}
	
	@RequestMapping(value = "user/dologin", method=RequestMethod.POST)
	public ModelAndView doLogin(
			HttpServletRequest request,
			@RequestParam("email") String email,
			@RequestParam("password") String password
			) {
		ModelAndView modelAndView = new ModelAndView();
		User user = userService.login(email, password, request.getRemoteAddr());
		
		if(user == null) {
			modelAndView.setViewName(PAGE_LOGIN);
			modelAndView.addObject("info", "邮箱或密码错误！");
			return modelAndView;
		}
		if(!user.isActicate()){
			modelAndView.setViewName(PAGE_ACTIVE_EMAIL);
			modelAndView.addObject("email", email);
			return modelAndView;
		}
	
		modelAndView.setViewName(PAGE_USER_HOME);
		modelAndView.addObject("user", user);
		return null;
	}
}
